import os
import ast
import re


def generate_test_script(business_file_path, test_file_path):
    """
    根据pages目录下的测试用例，自动生成tests目录下的测试脚本
    
    :param business_file_path: pages目录下测试用例文件路径
    :param test_file_path: tests目录下生成的测试脚本路径
    """
    # 获取business文件名（不含扩展名）
    business_file_name = os.path.basename(business_file_path).replace('.py', '')
    
    # 读取business文件内容
    with open(business_file_path, 'r', encoding='utf-8') as f:
        business_code = f.read()
    
    # 解析business文件，提取类名和方法
    tree = ast.parse(business_code)
    class_names = [node.name for node in tree.body if isinstance(node, ast.ClassDef)]
    
    if not class_names:
        raise ValueError("未找到类定义")
    
    # 获取第一个类名作为主要业务类
    main_class_name = class_names[0]
    
    # 提取business类中的所有方法名（除了__init__和setUp等特殊方法）
    method_names = []
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef) and node.name == main_class_name:
            for item in node.body:
                if isinstance(item, ast.FunctionDef) and not item.name.startswith('__'):
                    method_names.append(item.name)
    
    # 生成测试脚本内容
    test_methods = ""
    for i, method_name in enumerate(method_names, 1):
        test_methods += f'''    def {method_name}(self):
        # 执行{method_name}操作，登录已在 setUp 中进行
        operation = {main_class_name}(self.driver)
        operation.{method_name}()\n\n'''

    # 处理测试类名
    if main_class_name == "TestAndroid":
        test_class_name = "TestAndroidTest"
    else:
        # 移除文件名前缀并添加Test前缀
        # 例如: DemoPage.py中的DemopagePage类应该生成TestDemopagePage类
        test_class_name = f"Test{main_class_name}"
        
    test_script_content = f'''from pages.{business_file_name} import {main_class_name}
from utils.base_test import BaseTest


class {test_class_name}(BaseTest):
{test_methods}'''

    # 写入测试脚本文件
    with open(test_file_path, 'w', encoding='utf-8') as f:
        f.write(test_script_content)
    
    print(f"测试脚本已生成: {test_file_path}")


def auto_generate_all_tests():
    """自动生成所有pages目录下的测试脚本"""
    # 获取项目根目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(current_dir)
    
    # 构建正确的目录路径
    pages_dir = os.path.join(project_root, "pages")
    tests_dir = os.path.join(project_root, "tests")
    
    # 检查pages目录是否存在
    if not os.path.exists(pages_dir):
        raise FileNotFoundError(f"Pages目录不存在: {pages_dir}")
    
    # 确保tests目录存在
    os.makedirs(tests_dir, exist_ok=True)
    
    # 遍历pages目录下的所有Python文件
    for file_name in os.listdir(pages_dir):
        if file_name.endswith('.py') and not file_name.startswith('__'):
            pages_file_path = os.path.join(pages_dir, file_name)
            # 生成测试文件名
            if file_name == 'android.py':
                test_file_name = "test_android.py"
            else:
                test_file_name = f"test_{file_name}"
            test_file_path = os.path.join(tests_dir, test_file_name)
            
            try:
                generate_test_script(pages_file_path, test_file_path)
            except Exception as e:
                print(f"生成测试脚本失败: {test_file_path}, 错误: {e}")


if __name__ == "__main__":
    # 自动生成所有测试脚本
    auto_generate_all_tests()